<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item label="日期">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="仓库类型" prop="reType">
        <el-select v-model="query.reType" placeholder="请选择" @change="e => getStoreList(e)">
          <el-option :value="1" label="门市" />
          <el-option :value="3" label="场站" />
          <el-option :value="6" label="其他" />
        </el-select>
      </el-form-item>
      <el-form-item label-width="0">
        <el-select v-model="query.inStoreId">
          <el-option v-for="item in storeList" :key="item.storeId" :value="item.storeId" :label="item.storeName" />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      :summary-method="getSummaries"
      :immediate-fetch="false"
      show-summary
      @fetch="fetchData"
    />
    <detail ref="detail" />
  </div>
</template>

<script>
  import { queryScanBottleStatistics, queryExportScanBittleList, queryMap, queryStoreListByReType } from '@/api'
  import { formatColumnMap } from '@/utils'
  import { mapGetters } from 'vuex'
  import moment from 'dayjs'
  import Detail from './components/Detail'

  export default {
    name: 'scanStatistics',
    components: { Detail },
    compoments: {
      Detail
    },
    data() {
      return {
        date: [moment().startOf('day'), moment().endOf('day')],
        query: {
          reType: 1,
          inStoreId: ''
        },
        billTypeMap: { 11: '装车', 12: '卸车', 13: '领瓶', 14: '还瓶', 16: '配送签收', 17: '配送收回', 18: '欠瓶收回', 19: '用户退瓶' },
        gdStatusMap: [],
        storeList: [],
        tableData: {
          total: 0,
          column: [
            {
              prop: 'goodsName',
              label: '商品',
              width: 150
            },
            {
              prop: 'gdStatus',
              label: '状态',
              render: (h, { row }) => <span>{ row.gdStatus && formatColumnMap(this.gdStatusMap, 'value', row.gdStatus, 'desc') }</span>
            },
            {
              prop: 'loadCount',
              label: '装车',
              align: 'right',
              render: (h, { row }) => row.loadCount ? <el-link onClick={() => this.openDetail(row, '装车', 11)}>{row.loadCount}</el-link> : <span>{row.loadCount}</span>
            },
            {
              prop: 'unloadCount',
              label: '卸车',
              align: 'right',
              render: (h, { row }) => row.unloadCount ? <el-link onClick={() => this.openDetail(row, '卸车', 12)}>{row.unloadCount}</el-link> : <span>{row.unloadCount}</span>
            },
            {
              prop: 'getCount',
              label: '领瓶',
              align: 'right',
              render: (h, { row }) => row.getCount ? <el-link onClick={() => this.openDetail(row, '领瓶', 13)}>{row.getCount}</el-link> : <span>{row.getCount}</span>
            },
            {
              prop: 'returnCount',
              label: '还瓶',
              align: 'right',
              render: (h, { row }) => row.returnCount ? <el-link onClick={() => this.openDetail(row, '还瓶', 14)}>{row.returnCount}</el-link> : <span>{row.returnCount}</span>
            },
            {
              prop: 'signCount',
              label: '配送签收',
              align: 'right',
              render: (h, { row }) => row.signCount ? <el-link onClick={() => this.openDetail(row, '配送签收', 16)}>{row.signCount}</el-link> : <span>{row.signCount}</span>
            },
            {
              prop: 'signBackCount',
              label: '配送收回',
              align: 'right',
              render: (h, { row }) => row.signBackCount ? <el-link onClick={() => this.openDetail(row, '配送收回', 17)}>{row.signBackCount}</el-link> : <span>{row.signBackCount}</span>
            },
            {
              prop: 'oweBackCount',
              label: '欠瓶收回',
              align: 'right',
              render: (h, { row }) => row.oweBackCount ? <el-link onClick={() => this.openDetail(row, '欠瓶收回', 18)}>{row.oweBackCount}</el-link> : <span>{row.oweBackCount}</span>
            },
            {
              prop: 'userBackCount',
              label: '用户退瓶',
              align: 'right',
              render: (h, { row }) => row.userBackCount ? <el-link onClick={() => this.openDetail(row, '用户退瓶', 19)}>{row.userBackCount}</el-link> : <span>{row.userBackCount}</span>
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'exportDomain'
      ])
    },
    async created() {
      await Promise.all([this.queryOptionsMap(), this.getStoreList(1)])
      this.fetchData()
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData() {
        const query = {
          ...this._getQuery(this.query)
        }
        if (this.date && this.date.length > 0) {
          query.operatorTime = moment(this.date[0]).format()
          query.operatorTimeEnd = moment(this.date[1]).format()
        }
        if (query.inStoreId) query.outStoreId = this.query.inStoreId
        const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
        if (diff > 93) {
          this.$message.warning('请选择日期相差三个月之内')
          return
        }
        const res = await queryScanBottleStatistics(query)
        this.tableData.data = res.data
      },
      // 根据仓库类型查询仓库列表
      async getStoreList(reType) {
        const res = await queryStoreListByReType({ reType })
        this.storeList = res.data
        if (res.data.length > 0) this.query.inStoreId = res.data[0].storeId
      },
      async queryOptionsMap() {
        const res = await queryMap({ enumName: 'GdStatus' })
        this.gdStatusMap = res.data
      },
      async openDetail(row, title, billType) {
        await this.$refs.detail.open(row, title, this.date, billType, this.query)
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'info'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryExportScanBittleList({
            paramInfo: _this._getQuery(_this.query),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 合计方法
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '合计'
            return
          }
          if (column.property === 'gdStatus') {
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          }
        })
        return sums
      },
      reset() {
        this.$refs.form.resetFields()
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
</style>
